import { RequestConfig } from '../../axios/types'
import { ElLoading } from 'element-plus'

interface requestInfo {
  isMark: boolean
  requestCount: number
}

interface RequestState {
  requestInfo: requestInfo
}
let loadingInstance: any

export const useRequestStore = defineStore('request', {
  state: (): RequestState => {
    return {
      requestInfo: {
        isMark: import.meta.env.VITE_OPEN_API_MASK === 'true', // 是否加载接口遮罩
        requestCount: 0 // 加载请求数量
      }
    }
  },
  getters: {
    getRequestInfo(): requestInfo {
      return this.requestInfo
    }
  },
  actions: {
    addRequest(config: RequestConfig) {
      if (this.requestInfo.isMark) {
        if (config?.noMask != true) {
          this.requestInfo.requestCount++
        }
        if (!loadingInstance && this.requestInfo.requestCount > 0) {
          loadingInstance = ElLoading.service({
            lock: true,
            text: '加载中...',
            background: 'rgba(0, 0, 0, 0.7)'
          })
        }
      }
    },
    removeRequest(config: RequestConfig) {
      if (this.requestInfo.isMark) {
        if (config?.noMask != true && this.requestInfo.requestCount > 0) {
          this.requestInfo.requestCount--
        }
        if (this.requestInfo && this.requestInfo.requestCount === 0 && loadingInstance) {
          loadingInstance.close()
          loadingInstance = null
        }
      }
    }
  },
  persist: false
})

export const useRequestStoreWithOut = () => {
  return useRequestStore(store)
}
